package com.andatsoft.laisim.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.entity.Song;
import com.andatsoft.laisim.service.PlayerService;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.Utils;
import com.andatsoft.laisim.view.SlideView;
import com.andatsoft.laisim.view.SlideView.OnSlideChangedListener;
import com.andatsoft.laisim.view.SlimProgressBar;
import com.andatsoft.laisim.view.SlimProgressBar.SlimProgressClicked;

public class LockScreenActivity extends BaseActivity {

	private TextView mTvUnlock;
	private SlideView mSlideView;
	private SlimProgressBar mSlimProgress;
	private TextView mTvCurrentDuration;
	private TextView mTvTotalDuration;
	private TextView mTvTitle;
	private TextView mTvArtist;
	private Button mBtnPlay;
	private Button mBtnPrev;
	private Button mBtnNext;
	private ImageView mImgViewAlbumArt;
	private Handler mHandler = new Handler();

	// Player service
	private PlayerService mPlayerService;

	private ServiceConnection mPlayerServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mPlayerService = null;
		}

		// called when bind service called.
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPlayerService = ((PlayerService.LocalBinder) service).getService();
			if (mPlayerService != null) {
				mPlayerService.sendBroadCastSongInfoData();
			}
		}
	};

	private boolean mIsBoundService;

	public void doBindService() {
		bindService(new Intent(LockScreenActivity.this, PlayerService.class),
				mPlayerServiceConnection, Context.BIND_AUTO_CREATE);
		// Log.d("Bind", "bind" + bo);
		mIsBoundService = true;
	}

	public void doUnBindService() {
		unbindService(mPlayerServiceConnection);
		mIsBoundService = false;
	}

	private BroadcastReceiver mBroadcastUpdateSongInfo = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null) {
				return;
			}
			Song s = mPlayerService.getCurrentSong();
			if (s == null)
				return;
			mTvTitle.setText(s.getTitle());
			mTvArtist.setText(s.getArtist());
			mSlimProgress.setMax(s.getDuration());
			String curDurStr = Utils.convertTimeToString(s.getDuration());
			mTvTotalDuration.setText(curDurStr);
			updatePlayingStatus();
			updateAlbumArt(s.extractAlbumArt(getApplicationContext()));
		}
	};

	private BroadcastReceiver mBroadcastPauseStopSong = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null)
				return;
		}
	};

	private BroadcastReceiver mBroadcastUpdatePlayedTime = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (mPlayerService == null)
				return;
			int curDur = intent.getIntExtra(
					Common.BROADCAST_SONG_CURRENT_DURATION, 0);
			mSlimProgress.setProgress(curDur);
			String curDurStr = Utils.convertTimeToString(curDur);
			mTvCurrentDuration.setText(curDurStr);
		}
	};

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// hide navigation bar on android 4.0, API level 14
		if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			View decorView = getWindow().getDecorView();
			decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_FULLSCREEN);
		}
		setContentView(R.layout.activity_lock_screen);
		initViews();
		setupListeners();
		updateDateTime();
		updateSlideLock();
		updateSeekBar();
	}

	private void initViews() {
		mTvCurrentDuration = (TextView) findViewById(R.id.tv_lock_screen_played_time);
		mTvTotalDuration = (TextView) findViewById(R.id.tv_lock_screen_total_time);
		mTvTitle = (TextView) findViewById(R.id.tv_lock_screen_title);
		mTvArtist = (TextView) findViewById(R.id.tv_lock_screen_artist);

		mSlimProgress = (SlimProgressBar) findViewById(R.id.progress_lock_screen);
		mBtnPlay = (Button) findViewById(R.id.btn_lock_screen_play);
		mBtnPrev = (Button) findViewById(R.id.btn_lock_screen_previous);
		mBtnNext = (Button) findViewById(R.id.btn_lock_screen_next);
		mImgViewAlbumArt = (ImageView) findViewById(R.id.img_lock_screen_album_art);

	}

	private void setupListeners() {

		mBtnPlay.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (getSelectedSkin() == null)
						return true;
					if (getSelectedSkin().getPauseBtnPressed() == null)
						return true;
					if (mPlayerService != null && !mPlayerService.isFading()) {
						if (mPlayerService.isPlaying()) {
							setDrawableForView(mBtnPlay, getSelectedSkin()
									.getPauseBtnPressed());
						} else {
							setDrawableForView(mBtnPlay, getSelectedSkin()
									.getPlayBtnPressed());
						}
					}
					return true;
				case MotionEvent.ACTION_UP:
					if (mPlayerService == null) {
						setDrawableForView(mBtnPlay, getSelectedSkin()
								.getPlayBtnNormal());
						return true;
					}
					if (mPlayerService.getSongList() == null
							|| mPlayerService.getSongList().size() < 1) {
						setDrawableForView(mBtnPlay, getSelectedSkin()
								.getPlayBtnNormal());
						return true;
					}
					if (mPlayerService != null && !mPlayerService.isFading()) {
						if (mPlayerService.isPlaying()) {
							mPlayerService.pause(true);
							// if skin available
							if (getSelectedSkin() != null
									&& ((BitmapDrawable) getSelectedSkin()
											.getPlayBtnNormal()).getBitmap() != null
									&& !((BitmapDrawable) getSelectedSkin()
											.getPlayBtnNormal()).getBitmap()
											.isRecycled()) {
								setDrawableForView(mBtnPlay, getSelectedSkin()
										.getPlayBtnNormal());
							} else {
								mBtnPlay.setBackgroundResource(R.drawable.btn_lock_screen_play);
							}
						} else {
							mPlayerService.start();
							// if skin available
							if (getSelectedSkin() != null
									&& ((BitmapDrawable) getSelectedSkin()
											.getPauseBtnNormal()).getBitmap() != null
									&& !((BitmapDrawable) getSelectedSkin()
											.getPauseBtnNormal()).getBitmap()
											.isRecycled()) {
								setDrawableForView(mBtnPlay, getSelectedSkin()
										.getPauseBtnNormal());
							} else {
								mBtnPlay.setBackgroundResource(R.drawable.btn_lock_screen_pause);
							}

						}

					}

				}
				return false;
			}
		});

		mBtnPrev.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setDrawableForView(mBtnPrev, getSelectedSkin()
							.getPrevBtnPressed());
					return true;
				case MotionEvent.ACTION_UP:
					setDrawableForView(mBtnPrev, getSelectedSkin()
							.getPrevBtnNormal());
					if (mPlayerService != null) {

						if (!mPlayerService.isFading()) {
							mPlayerService.playPrevious();
						}
						mPlayerService.savePlayerSetting();
					}
					return true;
				}
				return false;
			}
		});

		mBtnNext.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent mE) {
				switch (mE.getAction()) {
				case MotionEvent.ACTION_DOWN:
					setDrawableForView(mBtnNext, getSelectedSkin()
							.getNextBtnPressed());
					return true;
				case MotionEvent.ACTION_UP:
					setDrawableForView(mBtnNext, getSelectedSkin()
							.getNextBtnNormal());
					if (mPlayerService != null) {

						if (!mPlayerService.isFading()) {
							mPlayerService.playNext();
						}
						mPlayerService.savePlayerSetting();
					}

					return true;
				}
				return false;
			}
		});
		mSlimProgress.setOnSlimClicked(new SlimProgressClicked() {

			@Override
			public void onClick(int newProgress) {
				if (mPlayerService == null)
					return;
				mPlayerService.playTo(newProgress);
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
				|| (keyCode == KeyEvent.KEYCODE_POWER)
				|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
				|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
			return false;
		}
		if ((keyCode == KeyEvent.KEYCODE_HOME)) {
			return true;
		}

		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(mBroadcastUpdatePlayedTime, new IntentFilter(
				Common.INTENT_UPDATE_TIME_PLAYED));
		registerReceiver(mBroadcastUpdateSongInfo, new IntentFilter(
				Common.INTENT_UPDATE_SONG_INFO));
		registerReceiver(mBroadcastPauseStopSong, new IntentFilter(
				Common.INTENT_STOP_SONG));
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mBroadcastUpdatePlayedTime != null)
			unregisterReceiver(mBroadcastUpdatePlayedTime);
		if (mBroadcastUpdateSongInfo != null)
			unregisterReceiver(mBroadcastUpdateSongInfo);
		if (mBroadcastPauseStopSong != null)
			unregisterReceiver(mBroadcastPauseStopSong);
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (!mIsBoundService)
			doBindService();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mIsBoundService)
			doUnBindService();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(updateCurrentTime);
	}

	private TextView mTvTime;
	private TextView mTvTimeAPM;
	private TextView mTvDate1;
	private TextView mTvDate2;

	private void updateDateTime() {
		SharedPreferences sp = getSharedPreferences(
				Common.SP_LOCK_SCREEN_SETTING_NAME, Context.MODE_PRIVATE);
		boolean showDate = sp.getBoolean(
				Common.SP_LOCK_SCREEN_SETTING_SHOW_DATE_TIME, true);

		if (!showDate) {
			return;
		}
		mTvTime = (TextView) findViewById(R.id.tv_lock_screen_time);
		mTvTimeAPM = (TextView) findViewById(R.id.tv_lock_screen_time_apm);
		mTvDate1 = (TextView) findViewById(R.id.tv_lock_screen_date_1);
		mTvDate2 = (TextView) findViewById(R.id.tv_lock_screen_date_2);

		Date dt = new Date();

		SimpleDateFormat sdf = new SimpleDateFormat("hh : mm",
				Locale.getDefault());
		String timeStr = sdf.format(dt);
		mTvTime.setText(timeStr);

		sdf = new SimpleDateFormat("a", Locale.getDefault());
		String timeAMP = sdf.format(dt);
		mTvTimeAPM.setText(timeAMP + "");

		sdf = new SimpleDateFormat("EEEE", Locale.getDefault());
		String date1 = sdf.format(dt);
		mTvDate1.setText(date1 + "");

		sdf = new SimpleDateFormat("MMMM d", Locale.getDefault());
		String date2 = sdf.format(dt);
		mTvDate2.setText(date2 + "");
		mHandler.post(updateCurrentTime);
	}

	private Runnable updateCurrentTime = new Runnable() {

		@Override
		public void run() {
			Date dt = new Date();

			SimpleDateFormat sdf = new SimpleDateFormat("hh : mm",
					Locale.getDefault());
			String timeStr = sdf.format(dt);
			mTvTime.setText(timeStr);

			sdf = new SimpleDateFormat("a", Locale.getDefault());
			String timeAMP = sdf.format(dt);
			mTvTimeAPM.setText(timeAMP + "");
			mHandler.postDelayed(updateCurrentTime, 30000);
		}
	};

	private void updatePlayingStatus() {
		if (mPlayerService == null)
			return;
		// if skin available
		if (getSelectedSkin() != null
				&& ((BitmapDrawable) getSelectedSkin().getPlayBtnNormal())
						.getBitmap() != null
				&& !((BitmapDrawable) getSelectedSkin().getPlayBtnNormal())
						.getBitmap().isRecycled()) {
			if (mPlayerService.isPlaying()) {
				setDrawableForView(mBtnPlay, getSelectedSkin()
						.getPauseBtnNormal());
			} else {
				setDrawableForView(mBtnPlay, getSelectedSkin()
						.getPlayBtnNormal());
			}
			setDrawableForView(mBtnPrev, getSelectedSkin().getPrevBtnNormal());
			setDrawableForView(mBtnNext, getSelectedSkin().getNextBtnNormal());
		} else {
			if (mPlayerService.isPlaying()) {
				mBtnPlay.setBackgroundResource(R.drawable.btn_lock_screen_pause);
			} else {
				mBtnPlay.setBackgroundResource(R.drawable.btn_lock_screen_play);
			}
		}
	}

	private void updateAlbumArt(Bitmap aa) {
		SharedPreferences sp = getSharedPreferences(
				Common.SP_LOCK_SCREEN_SETTING_NAME, Context.MODE_PRIVATE);
		boolean showAlbumArt = sp.getBoolean(
				Common.SP_LOCK_SCREEN_SETTING_SHOW_ALBUM_ART, false);
		if (showAlbumArt) {
			mImgViewAlbumArt.setImageBitmap(aa);
		} else {
			mImgViewAlbumArt
					.setImageResource(R.drawable.img_laisim_lock_screen_album_default);
		}
	}

	private void updateSlideLock() {
		SharedPreferences sp = getSharedPreferences(
				Common.SP_LOCK_SCREEN_SETTING_NAME, Context.MODE_PRIVATE);
		boolean slide = sp.getBoolean(
				Common.SP_LOCK_SCREEN_SETTING_SLIDE_TO_UNLOCK, true);

		if (!slide) {
			((SlideView) findViewById(R.id.slide_lock_screen))
					.setVisibility(View.GONE);
			((LinearLayout) findViewById(R.id.layout_lock_screen_press_to_unlock))
					.setVisibility(View.VISIBLE);
			mTvUnlock = (TextView) findViewById(R.id.tv_lock_screen_unlock);
			mTvUnlock.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View view, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						setAlpha(view, 0.5f);
						return true;
					case MotionEvent.ACTION_UP:
						setAlpha(view, 1.0f);
						LockScreenActivity.this.finish();
						return true;
					case MotionEvent.ACTION_CANCEL:
						setAlpha(view, 1.0f);
						return true;
					}

					return false;
				}
			});
		} else {
			mSlideView = (SlideView) findViewById(R.id.slide_lock_screen);
			mSlideView.setVisibility(View.VISIBLE);
			((LinearLayout) findViewById(R.id.layout_lock_screen_press_to_unlock))
					.setVisibility(View.GONE);
			mSlideView.setOnSlideChanged(new OnSlideChangedListener() {

				@Override
				public void onSlideEnded() {
					LockScreenActivity.this.finish();
				}
			});
		}
	}

	private void updateSeekBar() {
		SharedPreferences sp = getSharedPreferences(
				Common.SP_LOCK_SCREEN_SETTING_NAME, Context.MODE_PRIVATE);
		boolean showSeekbar = sp.getBoolean(
				Common.SP_LOCK_SCREEN_SETTING_SHOW_SEEK_BAR, true);

		if (!showSeekbar) {
			mSlimProgress.setVisibility(View.INVISIBLE);
		} else {
			mSlimProgress.setVisibility(View.VISIBLE);
		}
	}
}
